package com.neolix.watch.BroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import com.neolix.watch.NeolixApplication;
import com.neolix.watch.bluetooth.BlueToothUtil;
import com.neolix.watch.domain.NotificationType;
import com.neolix.watch.util.CommonHelper;
import com.neolix.watch.util.SharedPreferencesUtil;

import static com.neolix.watch.util.StringUtil.isBlank;
import static com.neolix.watch.util.StringUtil.isNotBlank;

public class SmsMessageReceiver extends BroadcastReceiver {
    public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

    private static final String SMS_FLAG = "pdus";
    private String TAG = SmsMessageReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        String smsAction = intent.getAction();
        if (isBlank(smsAction)) {
            return;
        }

        if (!smsAction.equals(SMS_RECEIVED))
            return;

        Bundle extras = intent.getExtras();
        if (extras == null) {
            return;
        }

        Object[] puds = (Object[]) intent.getExtras().get(SMS_FLAG);
        SmsMessage[] messages = new SmsMessage[puds.length];

        for (int i = 0; i < puds.length; i++) {
            messages[i] = SmsMessage.createFromPdu((byte[]) puds[i]);
        }

        for (SmsMessage message : messages) {
            String address = message.getDisplayOriginatingAddress();
            if (address.length() > 11)
                address = address.substring(address.length() - 11, address.length());

            Log.i(TAG, "电话号码:" + address + "短信内容：" + message.getDisplayMessageBody());
            if (SharedPreferencesUtil.isSendSMSInfo()) {
                //TODO 发送到手表
                String number = CommonHelper.getContactNameByPhoneNumber(NeolixApplication.getInstance(), address);
                BlueToothUtil.syncNotification(NotificationType.SMS, isNotBlank(number) ? number : address, message.getDisplayMessageBody());
            }
        }
    }
}
